#pragma once

#include <cstdio> // snprintf
#include <sys/time.h>
#include <chrono>
#include <ctime>

namespace txinfer {

// 2024-05-28T16:15:18.567234
constexpr std::size_t k_date_time_len = 19; // datetime length
constexpr std::size_t k_micro_len = 7;      // fraction length + .
constexpr std::size_t k_time_len = k_date_time_len + k_micro_len;

inline void PrintTimeToBuffer(char* buffer, const std::chrono::high_resolution_clock::time_point& p) {
  auto t = std::chrono::high_resolution_clock::to_time_t(p);
  std::strftime(buffer, k_date_time_len + 1, "%Y-%m-%dT%H:%M:%S", std::gmtime(&t));
  auto fraction = p - std::chrono::time_point_cast<std::chrono::seconds>(p);

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat-truncation"
  std::snprintf(buffer + k_date_time_len, k_micro_len + 1, ".%06d",
                static_cast<int>(fraction / std::chrono::microseconds(1)));
#pragma GCC diagnostic pop
}

} // namespace txinfer
